package com.jade.bss.ec.ware.impl;

import java.util.List;

import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.jade.bss.ec.ware.WareException;
import com.jade.bss.ec.ware.WareImage;
import com.jade.bss.ec.ware.WareImageDao;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.Restrictions;
import com.jade.framework.base.criterion.sql.SqlUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;

/**
 * 采用JPA方式商品图片数据访问接口。
 */
@Named ("bss_wareImageDao")
public class JpaImageDao
        implements WareImageDao
{
    protected static final String SQL_IMAGE = "SELECT wareImage FROM com.jade.bss.ec.ware.WareImage wareImage";
    @PersistenceContext (unitName = "default")
    protected EntityManager entityManager;

    @Caching (evict = {@CacheEvict (value = "bss.ec.ware.image.g", key = "#image.id"),
            @CacheEvict (value = "bss.ec.ware.image.l", key = "#image.wareId + '[%GRP%]'")})
    public void addImage(WareImage image)
            throws WareException
    {
        entityManager.persist(image);
    }

    @Caching (evict = {@CacheEvict (value = "bss.ec.ware.image.g", key = "#image.id"),
            @CacheEvict (value = "bss.ec.ware.image.l", key = "#image.wareId + '[%GRP%]'")})
    public void removeImage(WareImage image)
            throws WareException
    {
        WareImage old = getImage(image.getId());
        if (old != null) {
            entityManager.remove(old);
        }
    }

    @Caching (evict = {@CacheEvict (value = "bss.ec.ware.image.g", allEntries = true),
            @CacheEvict (value = "bss.ec.ware.image.l", key = "wareId + '[%GRP%]'")})
    public void removeImage(long wareId)
            throws WareException
    {
        String sql = "DELETE FROM com.jade.bss.ec.ware.WareImage WHERE wareId=:wid";
        Query query = entityManager.createQuery(sql);
        query.setParameter("wid", wareId);
        query.executeUpdate();
    }

    @Cacheable (value = "bss.ec.ware.image.g", key = "#id")

    public WareImage getImage(long id)
    {
        return entityManager.find(WareImage.class, id);
    }

    @Cacheable (value = "bss.ec.ware.image.l", key = "#wareId + '[%GRP%]' + #criteria")
    public List<WareImage> listImage(long wareId, Criteria criteria)
    {
        criteria.add(Restrictions.eq("wareId", wareId));
        return SqlUtils.sqlQueryWithoutCount(SQL_IMAGE, entityManager, criteria);
    }
}
